'use strict';
const urlJoin = require('url-join');
const axios = require('axios');
const semver = require('semver');

module.exports = {
  getNpmInfo,
  getDefaultRegistryUrl,
  getNpmVersions,
  getOnLineLatestVersion,
  getNpmLatestVersion
};

function getNpmInfo(packageName, registry) {
  if(!packageName) return null;

  const registryUrl = registry || getDefaultRegistryUrl();
  const npmInfoUrl = urlJoin(registryUrl, packageName)
  return axios.get(npmInfoUrl).then((response) => {
    if (response.status === 200) {
      return response.data;
    } else {
      return null;
    }
  }).catch((err) => {
    throw new Error(err.message)
  });;
}

function getDefaultRegistryUrl(isOrigin = true) {
  return isOrigin ? 'https://registry.npmjs.org' : 'https://registry.npm.taobao.org'
}

// 获取包所有的线上版本
async function getNpmVersions(packageName, registry) {
  const data = await getNpmInfo(packageName, registry);
  if(data) {
    return Object.keys(data.versions)
  } else {
    return []
  }
 }

 // getSemverVersions 获取所有超过baseVersion的版本
 function getSemverVersions(baseVersion, versions) {
  return versions.filter(version => semver.satisfies(version, `^${baseVersion}`))
  // 倒序排列
  .sort((a, b) => semver.gt(b, a) ? 1 : -1)
 }

 async function getOnLineLatestVersion(baseVersion, packageName, registry) {
  const version = await getNpmVersions(packageName, registry)
  const newVersions = getSemverVersions(baseVersion, version)
  if(newVersions && newVersions.length > 0) {
    return newVersions[0]
  }
 }

 async function getNpmLatestVersion(npmName, registry) {
   const versions = await getNpmVersions(npmName, registry)
   if(versions && versions.length > 0) {
    return versions.sort((a, b) => semver.gt(b, a) ? 1 : -1)[0]
   }
   return null
 }